/**
 * 地图定位初始化
 * 腾讯地图微信小程序
 * 百度地图定位H5
 * lat: 经度
 * lng: 纬度
 * city: 当前城市
 * province: 省份
 * nation:国家
 * district: 行政区
 * title:推荐的描叙地址更直观：如建筑物等
 * details:详细地址
 */
import local_addr from '@/util/address/local_addr.js'
import map_tx from '@/util/weixin/mp-weixin/map/qqmap-wx-jssdk.min.js'

let tengxunmapkey = "WGRBZ-BKWCF-BTYJ5-J62IA-XMAIE-LNFVG"
let addressList = [],
	defaultAddress = {}
let channel_from_h5 = true
// #ifdef MP-WEIXIN
channel_from_h5 = false
// #endif

//小程序地址获取
function getLocationWeixin(p) {
	uni.showLoading({
		mask: false
	})
	if (p.start) p.start()

	uni.getLocation({
		type: 'gcj02',
		success(res) {
			openAddress(res.latitude, res.longitude, p.success)
		},
		fail(res) {
			if (p.fail) p.fail()
		},
		complete() {
			uni.hideLoading()
			if (p.complete) p.complete()
		}
	});
};
//小程序端逆向解析地址
function openAddress(lat, lng, success) {
	let map = new map_tx({
		key: tengxunmapkey
	});
	map.reverseGeocoder({
		location: {
			latitude: lat,
			longitude: lng
		},
		success(res, data) {
			if (res.status == 0) {
				let result = data.reverseGeocoderSimplify;
				let map_tr = map_tx2bd(result.latitude, result.longitude)
				let address = {
					lat: map_tr.lat,
					lng: map_tr.lng,
					city: result.city,
					province: result.province,
					nation: result.nation,
					district: result.district,
					title: result.recommend || result.rough, //建筑物等
					details: result.address, //详细地址
					store: ''
				}
				local_addr.setAddr(address)
				if (success) success(address);

				console.log(result)
			}

		},
		complete(res) {

		}
	});
};

function map_tx2bd(lat, lng) {
	let x_pi = 3.14159265358979324 * 3000.0 / 180.0;
	let x = lng;
	let y = lat;
	let z = Math.sqrt(x * x + y * y) + 0.00002 * Math.sin(y * x_pi);
	let theta = Math.atan2(y, x) + 0.000003 * Math.cos(x * x_pi);
	let lngs = z * Math.cos(theta) + 0.0065;
	let lats = z * Math.sin(theta) + 0.006;
	return {
		lng: lngs,
		lat: lats
	}
}

//非小程序获取地址
function getMyloactionH5(p) {

	uni.showLoading({
		mask: false
	})
	if (p.start) p.start()

	var geolocation = new BMap.Geolocation();
	geolocation.getCurrentPosition(function(r) {
		uni.hideLoading()
		if (this.getStatus() == BMAP_STATUS_SUCCESS) {
			var lng = r.point.lng;
			var lat = r.point.lat;
			var addressdetails = r.address.city + r.address.district + r.address.street + r.address.street_number;
			let addr =
				reverseGeocoderH5({
					latitude: lat,
					longitude: lng,
					city: r.address.city,
					province: r.address.province || r.address.city,
					country: '中国',
					district: r.address.district || '',
					title: (r.address.street || '') + (r.address.street_number || ''), //建筑物等
					details: (r.address.street || '') + (r.address.street_number || ''), //详细地址
					store: ''
				})

			if (p.success) p.success(addr)
		} else if (p.fail) p.fail()
	}, {
		enableHighAccuracy: true,
		maximumAge: 18000,
		timeout: 18000
	});
};

//非小程序端逆向解析地址
function reverseGeocoderH5(addr = {}) {
	let address = {
		lat: addr.latitude,
		lng: addr.longitude,
		city: addr.city,
		province: addr.province,
		nation: addr.country,
		details: addr.details,
		title: addr.title, //建筑物等
		details: addr.details, //详细地址
		store: addr.store
	}
	local_addr.setAddr(address)

	return address
};


//获取我的地址
function getMyaddressList() {

}

export default {
	//定位位置 reload 是否重新请求 p:start,success,fail
	initMyLocation(reload = false, p = {}) {
		let init = () => {
			if (channel_from_h5) getMyloactionH5(p)
			else getLocationWeixin(p)
		}
		let localAddr = local_addr.getAddr();
		if (reload) {
			init()
		} else {
			if (localAddr && localAddr.title) {
				p.success(localAddr)
			} else init()
		}
	},
	//输入关键字检索地址
	getSuggestion(search = {}) {
		let keyword = search.keyword,
			city = search.city || '上海',
			pagesize = search.pagesize || 6;
		keyword = city + keyword


		let H5fn, Mpweixin;

		// #ifdef H5
		//h5端的检索
		H5fn = () => {

			uni.showLoading({
				mask: true
			})
			if (search.start) search.start()

			let options = {
				pageCapacity: pagesize,
				onSearchComplete: function(results) {
					uni.hideLoading()
					// 判断状态是否正确
					if (local.getStatus() == BMAP_STATUS_SUCCESS) {
						var s = [];
						for (var i = 0; i < results.getCurrentNumPois(); i++) {
							var resultItem = results.getPoi(i);
							if (resultItem.title && results.city == resultItem.title) {
								continue;
							}
							if (resultItem.tags && resultItem.tags.some(function(item) {
									return item == "公交车站"
								})) {
								continue;
							}
							s.push({ // 获取返回结果，放到sug数组中
								title: resultItem.title,
								details: resultItem.address,
								city: resultItem.city,
								district: "",
								province: resultItem.province,
								lat: resultItem.point.lat,
								lng: resultItem.point.lng,
								store: ''
							});
						}
						if (search.success) search.success(s)
					}
				}
			}
			let local = new BMap.LocalSearch(city, options);
			local.search(keyword);
		};
		// #endif

		// #ifdef MP-WEIXIN
		//小程序端的检索
		Mpweixin = () => {
			let qqmapsdk = new map_tx({
				key: tengxunmapkey
			});
			uni.showLoading({
				mask: true
			})
			//调用关键词提示接口
			qqmapsdk.getSuggestion({
				//获取输入框值并设置keyword参数
				keyword: keyword, //用户输入的关键词，可设置固定值,如keyword:'KFC'
				region: city, //设置城市名，限制关键词所示的地域范围，非必填参数
				page_size: pagesize,
				success: function(res) { //搜索成功后的回调
					var sug = [];
					for (var i = 0; i < res.data.length; i++) {
						if (res.data[i].type != 3 && res.data[i].type != 5) {
							sug.push({ // 获取返回结果，放到sug数组中
								title: res.data[i].title,
								details: res.data[i].address,
								city: res.data[i].city,
								district: res.data[i].district,
								province: res.data[i].province,
								lat: res.data[i].location.lat,
								lng: res.data[i].location.lng,
								store: ''
							});
						}
					}
					if (search.success) search.success(sug)
				},
				fail: function(error) {
					console.error(error);
					if (search.fail) search.fail()
				},
				complete: function(res) {
					uni.hideLoading()
					if (search.complete) search.complete()
				}
			});
		}
		// #endif
		if (channel_from_h5) H5fn()
		else Mpweixin()
	},
	//h5的地址解析 因为地址不全
	reverseGeocoder(addr = {}, callback) {

		// #ifdef H5
		uni.showLoading({
			mask: true
		})

		var geoc = new BMap.Geocoder();
		var point = new BMap.Point(addr.lng, addr.lat);

		geoc.getLocation(point, function(rs) {
			uni.hideLoading()
			var addComp = rs.addressComponents;

			console.log(addComp.province + ", " + addComp.city + ", " + addComp.district + ", " + addComp.street + ", " +
				addComp.streetNumber);

			addr.district = addComp.district
			local_addr.setAddr(addr)
			if (callback) callback()
		});
		// #endif

		// #ifdef MP-WEIXIN
		local_addr.setAddr(addr)
		if (callback) callback()
		// #endif
	}
}
